package com.imax.center.tcp;

import com.imax.center.service.DeviceDataService;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;
import java.util.Map;

@Slf4j
public class ClientHandler extends Thread {

    private final Socket socket;

    private final DeviceDataService deviceDataService;

    public ClientHandler(Socket _socket, DeviceDataService deviceDataService) {
        this.socket = _socket;
        this.deviceDataService = deviceDataService;
    }

    public void run() {
        try (InputStream input = socket.getInputStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(input));
             OutputStream output = socket.getOutputStream();
             PrintWriter writer = new PrintWriter(output, true)) {

            // 读取客户端发送的报文
            String message = reader.readLine();

            //判断message是否为##开头
            if (!message.startsWith("##")) {
                log.error("Invalid message format: {}", message);
                return;
            }

            //直接写氚云(异步)
            Map<String, Object> data = TcpDataUtil.parseData(message);
            deviceDataService.asyncHandlerEvent(message, data);

            //格式：##0000QN=20240319123456789;ST=32;CN=9012;PW=123456;MN=010000A8900016F000169DC0;Flag=4;CP=&&ExeRtn=1&&
            //构建响应报文
            assert data != null;
            String RESPONSE_OK = "QN="+ data.get("QN") +";ST="+ data.get("ST") +";CN="+ data.get("CN") +";PW="+ data.get("PW") +";MN="+ data.get("MN") +";Flag="+ data.get("Flag") +";CP=&&ExeRtn=1;ReCount=1&&";
            String lengthTo4 = String.format("%04d", RESPONSE_OK.length());
            RESPONSE_OK = "##" + lengthTo4 + RESPONSE_OK; //添加包头和报文长度
            writer.println(RESPONSE_OK); //响应客户端
        } catch (IOException ex) {
            log.error("Client handler exception: {}", ex.getMessage());
        } finally {
            try {
                socket.close();
            } catch (IOException ex) {
                log.error("Socket close exception: {}", ex.getMessage());
            }
        }
    }

}